extends Node
class_name LevelManager

@export var levels:Dictionary[String,Level]
var _current_level:Level
func _enter_tree() -> void:
	assert(levels)
func _ready() -> void:
	Global.save_game_level.connect(save)
func change_to_level(display_name:String)->void:
	if _load_from_save_if_have():return
	if levels.has(display_name):
		var ins:=levels[display_name]
		if not Global.debug:ins.load_in()
		else:ins.sample_load_in()
		_current_level=ins

func _load_from_save_if_have()->bool:
	if Global.enter_said_should_restart==true:
		return false
	if Global.debug:return false
	if FileAccess.file_exists(Global.save_path):
		var sc:PackedScene
		if ResourceLoader.load_threaded_get_status(Global.save_path)==ResourceLoader.THREAD_LOAD_LOADED:
			sc=ResourceLoader.load_threaded_get(Global.save_path)
		else:
			sc=load(Global.save_path)
		var ins:=sc.instantiate()
		ins.name="Begin"
		var inn:=get_child(0)
		remove_child(inn)
		add_child(ins)
		inn.queue_free()
		ins.load_in()
		_current_level=ins
		return true
	return false

func save()->void:
	var scene=PackedScene.new()
	var result:=scene.pack(_current_level)
	if result==OK:
		ResourceSaver.save(scene,Global.save_path)
